/*
 * This file is part of the Serial Flash Universal Driver Library.
 *
 * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Function: Portable interface for each platform.
 * Created on: 2016-04-23
 */

#include <sfud.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
// #include <stm32f4xx_hal.h>
#include "spi.h"
#include "dma.h"
#include "log.h"
#include "OSAL.h"
#include "mcu.h"

#ifdef FAL_USING_SFUD_PORT

typedef struct
{
    AP_SSI_TypeDef *SPIx;
    SPI_INDEX_e spi_index;
    GpioPin_t spi_cs_pin;
} spi_user_data, *spi_user_data_t;

static char log_buf[256];

void sfud_log_debug(const char *file, const long line, const char *format, ...);
//---------------------------------------------------------------------------
void dma_cb(DMA_CH_t ch)
{
    LOG("dma done\r\n");
}

HAL_DMA_t dma_cfg =
    {
        .dma_channel = SPI_DMAC_CH,
        .evt_handler = dma_cb,
};

static void spi_configuration(spi_user_data userSpiData)
{
    uint8_t retval = ERR_NONE;
    spi_Cfg_t cfg;
    HalDMAInit();
    retval = HalDMAInitChannel(dma_cfg);
    if (retval != ERR_NONE)
    {
        LOG("dma init err!\r\n");
    }

    // cfg.ssn_pin = P33;
    // cfg.sclk_pin = P1;
    // cfg.MISO = P34;
    // cfg.MOSI = P0;
    cfg.ssn_pin = userSpiData.spi_cs_pin;
    cfg.sclk_pin = P31;
    cfg.MISO = P33;
    cfg.MOSI = P32;

    cfg.baudrate = 400000;
    cfg.spi_tmod = SPI_TRXD;
    cfg.spi_scmod = SPI_MODE3; // SPI_MODE0;
    cfg.spi_dfsmod = SPI_1BYTE;
    cfg.dma_rx_enable = false;
    cfg.dma_tx_enable = false;
    cfg.int_mode = false;
    cfg.evt_handler = NULL;
    cfg.force_cs = true;
    cfg.is_slave = false;
    retval = HalSpiMasterConfig(userSpiData.SPIx, &cfg);
    if (retval != ERR_NONE)
    {
        LOG("spi init err!\r\n");
    }
    WaitMs(100);
    LOG("SPI Master Init\r\n");
}

static void spi_lock(const sfud_spi *spi)
{
    // __disable_irq();
    HAL_ENTER_CRITICAL_SECTION();
    // ;
}

static void spi_unlock(const sfud_spi *spi)
{
    // __enable_irq();
    HAL_EXIT_CRITICAL_SECTION();
    // ;
}

/**
 * SPI write data then read data
 */
static sfud_err spi_write_read(const sfud_spi *spi, const uint8_t *write_buf, size_t write_size, uint8_t *read_buf,
                               size_t read_size)
{
    sfud_err result = SFUD_SUCCESS;
    ErrCode_t state = ERR_NONE;
    spi_user_data_t spi_dev = (spi_user_data_t)spi->user_data;
    uint8_t *ptempWrite = NULL;
    if (write_size)
    {
        SFUD_ASSERT(write_buf);
        ptempWrite = (uint8_t *)osal_mem_alloc(write_size);
        if (ptempWrite)
        {
            osal_memcpy(ptempWrite, write_buf, write_size);
            // LOG("write buff alloc ok\r\n");
        }
        else
        {
            LOG("write buff alloc err\r\n");
            result = SFUD_ERR_WRITE;
            goto __exit;
        }
    }
    if (read_size)
    {
        SFUD_ASSERT(read_buf);
    }

    HalGpioSet(spi_dev->spi_cs_pin, Bit_DISABLE);

    if (write_size)
    {
        // state = HAL_SPI_Transmit(spi_dev->spi_handle, (uint8_t *)write_buf, write_size, 1000);
        state = UserSpiMasterTransfer(spi_dev->SPIx, SPI_TXD, ptempWrite, NULL, write_size);
        // while (HAL_SPI_GetState(spi_dev->spi_handle) != HAL_SPI_STATE_READY);
        osal_mem_free(ptempWrite);
        while (HalSpiGetTransmitState(spi_dev->spi_index))
            ;
    }

    if (state != ERR_NONE)
    {
        goto __exit;
    }

    if (read_size)
    {
        memset((uint8_t *)read_buf, 0xFF, read_size);
        // state = HAL_SPI_Receive(spi_dev->spi_handle, read_buf, read_size, 1000);
        // while (HAL_SPI_GetState(spi_dev->spi_handle) != HAL_SPI_STATE_READY);
        UserSpiMasterTransfer(spi_dev->SPIx, SPI_RXD, NULL, read_buf, read_size);
        while (HalSpiGetTransmitState(spi_dev->spi_index))
            ;
    }

    HalGpioSet(spi_dev->spi_cs_pin, Bit_ENABLE);
    // if (read_size && write_size) {
    //     memset((uint8_t *)read_buf, 0xFF, read_size);
    //     HalSpiMasterTransfer(spi_dev->SPIx, SPI_TRXD, NULL, read_buf, read_size);
    //     while(HalSpiGetTransmitState(spi_dev->spi_index));
    // }

__exit:
    return result;
}

/* about 100 microsecond delay */
static void retry_delay_100us(void)
{
    WaitUs(100);
}

static spi_user_data spi0 = {.SPIx = AP_SPI0, .spi_index = SPI0, .spi_cs_pin = P34};
sfud_err sfud_spi_port_init(sfud_flash *flash)
{
    sfud_err result = SFUD_SUCCESS;

    if (!strcmp(flash->spi.name, "SPI0"))
    {
        /* SPI Peripheral init*/
        spi_configuration(spi0);
        /* cs pin init */
        HalGpioFmuxEnable(spi0.spi_cs_pin, Bit_DISABLE);
        HalGpioSet(spi0.spi_cs_pin, Bit_ENABLE);
        HalGpioPupdConfig(spi0.spi_cs_pin, GPIO_PULL_UP);
        HalGpioPinInit(spi0.spi_cs_pin, GPIO_OUTPUT);

        /* ͬsynic flash driver and data*/
        flash->spi.wr = spi_write_read;
        flash->spi.lock = spi_lock;
        flash->spi.unlock = spi_unlock;
        flash->spi.user_data = &spi0;
        /* about 100 microsecond delay */
        flash->retry.delay = retry_delay_100us;
        /* adout 60 seconds timeout */
        flash->retry.times = 60 * 10000;
    }

    return result;
}

/**
 * This function is print debug info.
 *
 * @param file the file which has call this function
 * @param line the line number which has call this function
 * @param format output format
 * @param ... args
 */
void sfud_log_debug(const char *file, const long line, const char *format, ...)
{
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);
    LOG("[SFUD](%s:%ld) ", file, line);
    /* must use vprintf to print */
    vsnprintf(log_buf, sizeof(log_buf), format, args);
    LOG("%s\r\n", log_buf);
    va_end(args);
}

/**
 * This function is print routine info.
 *
 * @param format output format
 * @param ... args
 */
void sfud_log_info(const char *format, ...)
{
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);
    LOG("[SFUD]");
    /* must use vprintf to print */
    vsnprintf(log_buf, sizeof(log_buf), format, args);
    LOG("%s\r\n", log_buf);
    va_end(args);
}

#endif
